#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/8/1  17:52
# @Author: 余浪人
# @email: yulangren520@gmail.com
import jieba, datetime
import jieba.analyse
from datetime import datetime
from apps.api import api_bp
from flask import jsonify, request
from apps.api.public import save_img, apiErrors
from apps.lib.token import apiVerify_token
from apps.lib.public import get_date
from apps.models import db
from apps.models.content_model import TL_Column_model, TL_Content_Model
from apps.lib.public import add_tag


# 获取分类
from apps.webapi.webpublic.public import img


@api_bp.route('/column', methods=['GET'])
@apiVerify_token
def column():
    ColumnList = TL_Column_model.query.all()
    data = {
        "status": 0,
        "message": "获取分类成功",
        "columnList": [
            {
                "column_name": col.column_name,
                "column_id": col.id,
                "column_uuid": col.uuid,
                "column_order": col.column_order,
                "column_keyword": col.column_keyword,
                'column_description': col.column_description,
            }
            for col in ColumnList
        ]
    }
    return jsonify(data)


# 文档发布
@api_bp.route('/document', methods=['POST'])
@apiVerify_token
def document():
    data = request.json.get('data') if request.is_json else request.form.get('data')
    if data:
        try:
            if TL_Content_Model.query.filter(TL_Content_Model.title == data['title']).count():
                return jsonify({"status": 400, "msg": "文档标题已存在!"})
            col = TL_Column_model.query.filter_by(uuid=data['superior']).first()
            if apiErrors(col):
                return jsonify({"status": 404, "msg": "分类栏目不存在!"})
            data['content'] = save_img(data['content'])
            data['keyword'] = ','.join(jieba.cut_for_search(data['title'])) if not data['keyword'] else None
            data['update_time'] = data.get('update_time') if data.get('update_time') else datetime.now()
            data['thumb_img'] = img(data['thumb_img'], data['content'])
            data['superior'] = col.id
            try:
                con = TL_Content_Model()
                con.set_attrs(data)
                db.session.add(con)
                db.session.commit()
            except:
                db.session.rollback()
                return jsonify({"status": 401, "msg": "发布异常!"})
            keys = [x for x, _ in jieba.analyse.textrank(data['title'], withWeight=True)]
            add_tag(keys)
            return jsonify({"status": 0, "msg": "发布成功!"})
        except:
            return jsonify({"status": 404, "msg": "处理异常!"})
    return jsonify({"status": 403, "msg": "请添加发布数据!"})


# 删除分类
@api_bp.route('/column', methods=['DELETE'])
@apiVerify_token
def delete_column():
    data = request.json.get('data') if request.is_json else request.form.get('data')
    column_id = data.get('column_id')
    if data and isinstance(column_id, int):
        col_obj = TL_Column_model.query.filter_by(id=column_id).first()
        if apiErrors(col_obj): return apiErrors(col_obj)
        try:
            db.session.delete(col_obj)
            db.session.commit()
        except:
            db.session.rollback()
            return jsonify({"status": 400, "message": "删除异常"})
        return jsonify({"status": 0, "message": "删除成功"})
    return jsonify({"status": 401, "message": "请求异常"})
